#!/usr/bin/env python
#coding=utf-8

from codingabc.database import db

# 在super机制里可以保证公共父类仅被执行一次，至于执行的顺序，是按照mro进行的（E.__mro__）。
class MyModelService(object):
    """ MyModelService """

    def __init__(self):
        super(MyModelService, self).__init__()

    @classmethod
    def create(cls, commit=False, **kwargs):
        instance = cls(**kwargs)
        return instance.save(commit=commit)

    @classmethod
    def get(cls, id):
        return cls.query.get(id)

    @classmethod
    def get_or_404(cls, id):
        return cls.query.get_or_404(id)

    def update(self, commit=False, **kwargs):
        for attr, value in kwargs.iteritems():
            setattr(self, attr, value)
        return commit and self.save(commit=commit) or self

    def save(self, commit=False):
        db.session.add(self)
        if commit:
            db.session.commit()
        return self

    def delete(self, commit=False):
        db.session.delete(self)
        return commit and db.session.commit()

    @classmethod
    def name_dict(cls, id_name='', column_name_list=[]):
        """字段名称词典"""

        cls_list = cls.query.all()
        index = len(column_name_list)
        if index <= 1:
            NAME = {}
            column_name = column_name_list[0]
            for c in cls_list:
                id = getattr(c, id_name)
                name = getattr(c, column_name)
                NAME[id] = name
            return NAME
        else:
            name_dict_list = []
            for name_dict in column_name_list:
                name_dict = {}
                name_dict_list.append(name_dict)

            for c in cls_list:
                for i in range(index):
                    column_name = column_name_list[i]
                    id = getattr(c, id_name)
                    name = getattr(c, column_name)
                    name_dict_list[i][id] = name

            return name_dict_list
